<template>
	<view class="scan-pay">
		<view class="store">
			<image :src="info.logo" width="150" height="150"></image>
			<view class="name">{{info.name}}</view>
		</view>
		<view class="card fee">
			<view class="title">消费金额</view>
			<view class="bd">
				<view class="amount">
					<text class="unit">￥</text>
					<input class="value" type="digit" min="0.01" maxlength="12" v-model="formdata.total_amount"
						placeholder="请输入支付金额" auto-focus @input="calculatePrice" />
				</view>
			</view>
		</view>
		<view class="tips">请您在付款前确认商户信息及付款金额，并确保支付环境安全</view>
		<view class="card">
			<view class="title">消费红包</view>
			<view class="cell-item">
				<uni-icons type="icon-hongbao" custom-prefix="iconfont" size="24" color="#ff9900"></uni-icons>
				<view class="more">
					<text class="value">{{redpacket.total_money}}</text>
				</view>
			</view>
			<view class="tips">使用消费红包需要扣除{{redpacket.profit}}%的手续费，实际可用消费红包￥{{redpacket.balance_fee}}。</view>
		</view>
		<view class="pay-price">优惠后实付金额：￥{{formdata.pay_amount}}元</view>

		<button class="pay-btn" :disabled="payDisabled" @click="pay">{{payText}}</button>
		<!-- <button class="pay-btn" @click="refresh">刷新</button> -->
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import checkLogin from '@/utils/login';
	import {
		ref,
		reactive,
		toRefs,
		inject
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	// #ifdef H5
	// import jweixin from "jweixin-module";
	// #endif

	const web_host = inject('web_host');

	const state = reactive({
		themeColor: JSON.parse(cache.get('themeColor')),
		environment: {
			isWeChat: true,
			isAlipay: false,
			isBrowser: false,
		},
		info: {},
		redpacket: {
			total_money: 0,
			commission: 0,
			profit: 0,
			balance_fee: 0,
		},
		formdata: {
			store_id: 0, //门店id
			total_amount: '', //输入金额
			balance_amount: '', //使用红包
			pay_amount: '0', //实际付款金额
			coupon_id: 0, //使用优惠券列表
			remark: '门店扫码付款', //备注
		},
		payText: '确认支付',
		payDisabled: false,
		alipay_openid: '',
		bindMobile: false,
		fromType: 'h5',
		payWay: '1',
		pay_type: 0,
		order_id: '',
		trade_no: '',
		invite_code: '',
		phone: '',
	});

	onLoad((opt) => {
		// #ifdef H5
		state.environment = checkEnvironment();
		console.log('H5浏览器类型', state.environment)
		// #endif

		if (opt.hasOwnProperty('store_id')) {
			state.formdata.store_id = opt.store_id;
			getStoreInfo();
		} else {
			pageRoute('/pages/init/init');
		}

		if (opt.hasOwnProperty('invite_code')) {
			cache.set('invite_code', opt.invite_code);
			state.invite_code = opt.invite_code //是否扫推广码进入
		} else {
			state.invite_code = cache.get('invite_code') || state.invite_code;
		}

		//登录过期自动登录
		console.log('登录状态', checkLogin());
		if (!checkLogin()) {
			//未登录（静默登录，不需要弹窗）
			// #ifdef H5
			if (state.environment.isWeChat) {
				if (opt.hasOwnProperty('code')) {
					wxjsLogin(opt.code);
				} else {
					location.href = web_host +
						'/api/wxauth/getAuthCode?type=scancode&scope=snsapi_userinfo&store_id=' +
						state.formdata.store_id;
				}
			} else if (state.environment.isAlipay) {
				if (opt.hasOwnProperty('openid')) {
					state.alipay_openid = opt.openid;
					if (opt.hasOwnProperty('is_mobile')) {
						//已经关联账号自动登录
						aliLogin();
					} else {
						//未关联账号，通过手机号进行关联
						state.bindMobile = true;
					}
					console.log('openid', state.alipay_openid);
				} else {
					location.href = web_host +
						'/api/aliauth/getAuthCode?type=scancode&store_id=' +
						state.formdata.store_id;
				}
			}
			// #endif
			// #ifdef MP-WEIXIN
			//静默登录，已有账号直接登录，没有账号打开手机号授权登录
			wxLogin();
			// #endif
		} else {
			//登录成功获取余额
			getBalance();
		}
	});

	onShow(() => {});

	//开始支付
	function pay() {
		//支付前计算金额
		calculatePrice();
		if (state.formdata.total_amount == '') {
			uni.showToast({
				title: '没有输入消费金额',
				icon: 'fail'
			})
			return;
		}
		if (state.formdata.total_amount < 0.01) {
			uni.showToast({
				title: '最小金额不能小于0.01元',
				icon: 'fail'
			})
			return;
		}
		state.payDisabled = true;
		state.payText = '正在支付';

		if (state.environment.isAlipay) {
			state.fromType = 'alipay';
			state.payWay = '2';
		}
		// #ifdef MP-WEIXIN
		state.fromType = 'weixin';
		state.payWay = '1';
		// #endif
		// #ifdef APP
		state.fromType = 'app';
		state.payWay = '1';
		// #endif

		console.log('开始支付', state.formdata);
		setTimeout(function() {
			request.post('scanpay/submit', {
				store_id: state.formdata.store_id,
				remark: state.formdata.remark,
				balance_amount: state.formdata.balance_amount,
				pay_amount: state.formdata.pay_amount,
				total_amount: state.formdata.total_amount,
				coupon_id: state.formdata.coupon_id,
				from_type: state.fromType,
				pay_way: state.payWay,
				order_id: state.order_id
			}).then(res => {
				console.log('扫码支付', res);

				console.log("res.code", res.code)
				console.log("res.msg", res.msg)
				console.log("res.data", res.data)
				state.order_id = res.data.order_id;
				state.trade_no = res.data.trade_no;
				if (res.code == 1) {
					console.log('扫码支付-11', state.order_id, state.trade_no);
					uni.showToast({
						title: '订单创建成功！',
						icon: 'none'
					})
					doPay(res);
				} else if (res.code == 2) {
					console.log('扫码支付-22', state.order_id, state.trade_no);
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					doPay(res);
				} else {
					console.log('扫码支付-00', state.order_id, state.trade_no);
					uni.showToast({
						title: res.msg + "，订单已取消",
						icon: 'none'
					})
					//交易失败后，取消订单并返回红包
					cancel();
				}
			})
		}, 10);
	}

	//支付
	function doPay(res) {
		//余额支付
		if (state.formdata.pay_amount === 0) {
			state.payDisabled = false;
			state.payText = '确认支付';
			state.pay_type = 0; //余额支付
			uni.showToast({
				title: res.msg,
				duration: 2000
			});
			//支付成功的回调
			paySuccess();
		}

		//开始支付
		if (res.data.code == "000000") {
			// 微信小程序支付
			// #ifdef MP-WEIXIN
			state.pay_type = 1; //微信支付
			wxPay(res);
			// #endif
			// #ifdef H5
			// 微信H5支付
			if (state.environment.isWeChat) {
				state.pay_type = 1; //微信支付
				h5Pay(res);
			}
			// 支付宝H5支付
			if (state.environment.isAlipay) {
				state.pay_type = 2; //支付宝支付
				alipay(res);
			}
			// #endif
		}
	}

	//微信小程序支付
	function wxPay(resp) {
		uni.requestPayment({
			provider: 'wxpay',
			orderInfo: '',
			// appid: resp.data.data['jsapiAppid'], // 应用ID（AppID），由商户传入
			package: resp.data.data['jsapiPackage'], // 固定值
			nonceStr: resp.data.data['jsapiNoncestr'], // 随机字符串
			timeStamp: resp.data.data['jsapiTimestamp'], // 时间戳（单位：秒），自1970年以来的秒数
			signType: resp.data.data['jsapiSignType'], // 签名算法
			paySign: resp.data.data['jsapiPaySign'], // 签名
			success: function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					//支付成功的回调
					paySuccess();
				} else {
					if (res.err_msg == 'get_brand_wcpay_request:cancel') {
						uni.showModal({
							content: "交易取消，订单已取消",
							showCancel: false
						})
					} else {
						uni.showModal({
							content: "支付失败,原因为: " + res.err_msg + "，订单已取消",
							showCancel: false
						})
					}
					//交易取消或失败后，取消订单
					cancel();
				}
			},
			fail: function(err) {
				console.log(err);
				//支付失败后，取消订单
				cancel();
			}
		});
	}

	//微信H5支付
	function h5Pay(resp) {
		let jsApiParameters = {
			"appId": resp.data.data['jsapiAppid'], // 应用ID（AppID），由商户传入
			"package": resp.data.data['jsapiPackage'], // 固定值
			"nonceStr": resp.data.data['jsapiNoncestr'], // 随机字符串
			"timeStamp": resp.data.data['jsapiTimestamp'], // 时间戳（单位：秒），自1970年以来的秒数
			"signType": resp.data.data['jsapiSignType'], // 签名算法
			"paySign": resp.data.data['jsapiPaySign'] // 签名
		};
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', jsApiParameters,
			function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					//支付成功的回调
					paySuccess();
				} else {
					if (res.err_msg == 'get_brand_wcpay_request:cancel') {
						uni.showModal({
							content: "交易取消，订单已取消",
							showCancel: false
						})
						//交易取消或失败后，取消订单
						cancel();
					} else {
						uni.showModal({
							content: "支付失败,原因为: " + res.err_msg + "，订单已取消",
							showCancel: false,
							success: function(re) {
								if (re.confirm) {
									// 使用setTimeout来延迟关闭模态对话框
									setTimeout(function() {
										uni.hideLoading(); // 关闭模态对话框
										//交易取消或失败后，取消订单
										cancel();
									}, 3000);
								}
							}
						})
					}
				}
			}
		);
	}

	//支付宝H5支付
	function alipay(resp) {
		let tradeNO = resp.data.data.prepayid;
		AlipayJSBridge.call(
			"tradePay", {
				tradeNO: tradeNO
			},
			function(res) {
				if ("9000" == res.resultCode) {
					//支付成功的回调 
					paySuccess();
				} else {
					//支付取消或未成功，取消订单
					cancel();
				}
			});
	}

	//支付成功的回调
	function paySuccess() {
		request.post('scanpay/paySuccess', {
			trade_no: state.trade_no,
			pay_type: state.pay_type,
		}).then(r => {
			console.log('回调--222', r);
			uni.navigateTo({
				url: '/pages/users/commission/commission?currentTab=1'
			})
		});
	}

	//取消支付
	function cancel() {
		state.payDisabled = false;
		state.payText = '确认支付';
		request.post('scanpay/cancel', {
			id: state.order_id,
		}).then(res => {
			console.log('取消订单', res);
			state.order_id = '';
			state.trade_no = '';
			// window.location.reload();
		});
	}

	//刷新页面
	function refresh() {
		window.location.reload();
	}

	//微信H5登录
	function wxjsLogin(code) {
		request.post('wxauth/mpLogin', {
			code: code,
			invite_code: state.invite_code,
			store_id: state.formdata.store_id,
		}).then(res => {
			navigateToHandle(res);
		});
	}

	//支付宝H5登录
	function aliLogin() {
		request.post('aliauth/aliLogin', {
			mobile: state.phone,
			openid: state.alipay_openid
		}).then(res => {
			navigateToHandle(res);
		});
	}

	//微信小程序登录
	function wxLogin() {
		uni.login({
			provider: 'weixin',
			success: res => {
				appletLogin(res.code);
			}
		})
	}

	function appletLogin(code) {
		//自动登录
		request.post('wxauth/autoLogin', {
			code: code,
			invite_code: state.invite_code,
			store_id: state.formdata.store_id,
		}).then(res => {
			navigateToHandle(res);
		})
	}

	//登录成功
	function navigateToHandle(res) {
		if (res.code === 1) {
			cache.set('LOGIN_STATUS_TOKEN', res.token);
			uni.showToast({
				title: res.msg,
				icon: 'success'
			})
			getBalance();
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'error'
			})
		}
	}

	//获取门店信息
	function getStoreInfo() {
		request.get('store/info', {
			id: state.formdata.store_id,
		}).then(res => {
			console.log('Store', res);
			state.info = res.data;
			if (res.data.status !== 1) {
				state.payDisabled = true;
				uni.showToast({
					title: '该店铺已禁用或关闭',
					icon: 'fail'
				})

				// 延时3秒执行
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/tabbar/my/my'
					})
				}, 3000);
			}
			if (res.data.business_status === 0) {
				state.payDisabled = true;
				uni.showToast({
					title: '该店铺未营业',
					icon: 'fail'
				})

				// 延时3秒执行
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/tabbar/my/my'
					})
				}, 3000);
			}
		})
	}

	//获取余额
	function getBalance() {
		request.get('scanpay/getBalance').then(res => {
			console.log("获取余额", res);
			if (res.code == 1) {
				state.redpacket = res.data;
			}
		})
	}

	//失去焦点计算金额
	function calculatePrice() {
		request.post('scanpay/calculatePrice', {
			total_money: state.redpacket.total_money,
			total_amount: state.formdata.total_amount,
		}).then(res => {
			console.log('计算金额', res);
			if (res.code == 1) {
				state.formdata.pay_amount = res.data.pay_amount;
				state.formdata.balance_amount = res.data.balance_amount;
			} else {
				state.formdata.pay_amount = 0;
				state.formdata.balance_amount = 0;
			}
		})
	}

	//判断打开浏览器
	function checkEnvironment() {
		let userAgent = navigator.userAgent.toLowerCase();
		//判断是否是微信浏览器
		let isWeChat = userAgent.indexOf('micromessenger') !== -1;
		//判断是否是支付宝浏览器
		let isAlipay = userAgent.indexOf('alipayclient') !== -1;
		//判断是否是普通浏览器
		let isBrowser = !isWeChat && !isAlipay;

		return {
			isWeChat: isWeChat,
			isAlipay: isAlipay,
			isBrowser: isBrowser
		};
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.switchTab({
			url
		});
	};

	const {
		themeColor,
		environment,
		info,
		redpacket,
		formdata,
		payText,
		payDisabled,
		alipay_openid,
		bindMobile,
		fromType,
		payWay,
		order_id,
		trade_no,
		invite_code,
		phone,
	} = toRefs(state);
</script>

<style lang="scss">
	.scan-pay {
		@include f-center(column);
		padding: $m24 5%;

		.store {
			@include f-center(column);
			padding: $m24;

			.name {
				text-align: center;
				margin-top: $m12;
				font-size: $font-32;
			}
		}

		.card {
			// width: 100%;
			margin: $m24 0;
			padding: $m28;
			background-color: $u-bg-reverse-color;
			border-radius: $radius-24;

			&.fee {
				.bd {

					align-items: center;
					justify-content: flex-end;

					.amount {
						@include f-between;
						width: 100%;

						.unit {
							font-size: $font-36;
							line-height: 1.5;
						}

						.value {
							font-size: $font-36;
						}
					}
				}
			}

			.title {
				color: $u-main-color;
			}

			.fee {
				font-size: $font-36;
				color: $u-main-color;
				font-weight: 500;
				text-align: right;
			}

			.cell-item {
				@include f-between;
				padding: $m12 0;
				border-bottom: 1rpx solid $u-border-color;

				.more {
					position: absolute;
					left: 0rpx;
					width: 100%;
					text-align: center;

					.value {
						color: $u-content-color;
						font-size: $font-36;
						width: 100rpx;
					}
				}
			}
		}

		.tips {
			color: red;
			font-size: $font-24;
			padding-top: 10rpx;
			padding-bottom: 10rpx;
			text-align: center;
		}

		.pay-price {
			color: red;
			text-align: center;
			font-size: $font-36;
			font-weight: bold;
			padding-top: 20rpx;
		}

		.remark {
			@include f-between;
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 88rpx;
			padding: 0 $m24;
			background-color: $u-bg-reverse-color;

			.value {
				flex: 1;
				padding: 0 $m16;
			}
		}

		.pay-btn {
			margin-top: 20px;
			width: 100%;
			color: #ffffff;
			background: #ff9900;
		}
	}
</style>